package no21.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class T{
	private String a;
	private int i;
	public String getA(){
		return a;
	}
	public void setA(String b){
		a =b;
	}
	public int getI() {
		return i;
	}
	public void setI(int i) {
		this.i = i;
	}
	
}

public class WaitTest implements Runnable{
	private T t;
	private int count=0;
	public WaitTest(T t,int i){
		this.t =t;
		this.count = i;
	}
	@Override
	public void run() {
		try {
			print();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			System.out.println("InterruptedException"+e);
		}
		
	}
	
	/**
	 * 拥有t的对象锁时,将t挂起
	 * 拥有t的对象锁时,将t唤醒
	 * @throws InterruptedException
	 */
	private synchronized void print() throws InterruptedException{
		//奇数挂起
		if(count % 2 != 0){
			synchronized(t){
				//线程被挂起后,在此停止
				//被唤醒后,也由此继续执行
				//如果被唤醒时,不满足条件,继续wait
				while(t.getI() != 10){
					//测试其是是在此处循环等待(continue),不是,是挂起了
					//写循环的原因是,唤醒的地方可能不止一处,而每次唤醒都得重新判断条件
					System.out.println("loop i==>"+count);
					t.wait();
				}
			}
			System.out.println("this count ==>"+count);
		}
		
		if(count ==10){
			synchronized(t){
				//此时唤醒t的所有挂起线程
				t.notifyAll();
				System.out.println("last count");
			}
		}
	}
	public static void main(String[] args) {
		T t = new T();
		
		ExecutorService exec = Executors.newCachedThreadPool();
		for (int i = 0; i < 11; i++) {
			t.setI(i);
			t.setA("T t ==>"+i);
			exec.execute(new WaitTest(t,i));
		}
		try {
			TimeUnit.MILLISECONDS.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		exec.shutdown();
	}
	
}
